﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using Masuit.Tools.Security;
using System.Collections.Generic;
using PowerStation.RequestModel;
using Microsoft.EntityFrameworkCore;
using adb.excel;
using System.IO;
using Masuit.Tools;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNetCore.Authorization;
using System;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 模板管理
    /// </summary>
    public class TableTemplateController : BaseApi<TableTemplateController>
    {
        /// <summary>
        /// 模板管理
        /// </summary>
        /// <param name="content"></param>
        public TableTemplateController(IHttpContextAccessor content) : base(content)
        {
        }



        /// <summary>
        /// 报表列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tExcel>>> List()
        {
            IQueryable<tExcel> q = this._db.tExcel.Where(x=>x.dataState == 0);
            return ResultApi.ok<List<tExcel>>(await q.ToListAsync()) ;
        }


        /// <summary>
        /// 删除表格,注意删除就没有了,没有新增功能
        /// </summary>
        /// <param name="excelId">表格ID</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> Delete(decimal excelId)
        {
            await this._db.tExcel.Where(x => x.excelId == excelId).UpdateAsync(x => new tExcel { dataState = 1 });
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(true, true);
        }


        /// <summary>
        /// 表格详情
        /// </summary>
        /// <param name="typeId">表格类型ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tExcelTitle>>> Detial(decimal typeId)
        {
            var titles = await this._db.tExcelTitle.Where(x => x.excelType == typeId && x.dataState == 0).OrderBy(x=>x.excelTitleSort).ToListAsync();
            return ResultApi.ok<List<tExcelTitle>>(titles);
        }


        /// <summary>
        /// 表格详情
        /// </summary>
        /// <param name="typeId">表格类型,1:日志,2:用户信息,3:电站列表,4:生产信息日报,5:生产水情日报,6:生产信息月报,7:生产信息年报</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<RequestExcelDetailModel>> DetialOfType(int typeId)
        {
            var model = await this._db.tExcel.OrderByDescending(x=>x.excelId).FirstOrDefaultAsync(x => x.excelType == typeId && x.dataState == 0);
            if (model == null) return ResultApi.error<RequestExcelDetailModel>(null, "表格不存在");
            var titles = await this._db.tExcelTitle.Where(x => x.excelType == model.excelType && x.dataState == 0).ToListAsync();
            return ResultApi.ok<RequestExcelDetailModel>(new RequestExcelDetailModel { model = model, Lst = titles });
        }


        /// <summary>
        /// 下载模板
        /// </summary>
        /// <param name="typeId">表格类型,1:日志,2:用户信息,3:电站列表,4:生产信息日报,5:生产水情日报,6:生产信息月报,7:生产信息年报</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<FileStreamResult> Download(int typeId)
        {
            var m = new List<object>();
            var titles = await this._db.tExcelTitle.Where(x=>x.excelType == typeId).ToListAsync();
            if (titles.Count == 0) return new FileStreamResult(new MemoryStream(), new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            Task<Stream> task = Task.Run(async () => {
                return ExcelExport.export<object>(m, titles);
            });
            return new FileStreamResult(await task, new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }


        /// <summary>
        /// 获取系统报表类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tExcelTitle>>> ExcelTypeList()
        {
            IQueryable<tExcelTitle> q = this._db.tExcelTitle.GroupBy(x=>new { x.excelType,x.excelTypeName}).Select(x=>new tExcelTitle { 
                excelType = x.Key.excelType,
                excelTypeName = x.Key.excelTypeName,
            });
            return ResultApi.ok<List<tExcelTitle>>(await q.ToListAsync(), 0);
        }



        /// <summary>
        /// 检测上传的文件有没有问题
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<RequestExcelCheckModel>> CheckXmlFile([FromForm]RequestExcelModel model)
        {
            if (model.xlsFile.Length > 0)
            {
                var titles = await this._db.tExcelTitle.Where(x => x.excelType == model.typId).ToListAsync();
                if (titles.Count > 0)
                {

                    Task<Tuple<int, int, List<TableErrorModel>>> task = new Task<Tuple<int, int, List<TableErrorModel>>>(() =>
                    {
                        using (var stream = new MemoryStream())
                        {
                            model.xlsFile.CopyTo(stream);
                            return ExcelExport.checkInputData(titles, stream);
                        }
                    });
                    task.Start();
                    var lst = await task;
                    
                    return ResultApi.ok(new RequestExcelCheckModel { 
                        ErrorCount = lst.Item2,
                        SucccessCount = lst.Item1,
                        errorLst =lst.Item3
                    });
                }
            }
            return ResultApi.error<RequestExcelCheckModel>(null,"未接收到文件");
        }

    }
}
